// let utils = require('../../../../utils/util');
const { http } = require('../../../../utils/apiutils.js');
import { input } from '../../../../utils/tools'
const util = require("../../../../utils/util")
import { formatTime, formatTime1 } from '../../../../utils/util'
var height =0;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    searchQuery:{
      key:'',
    },
    img: [],
    img1: [],
    fileListImg: [],
    fileListImg1: [],
    allWork: [{
      key: '需求方',
      value: 1
    }, {
      key: '供给方',
      value: 2
    }],
    checked: true,
    form: {
      id: '',
      title: '',
      beFrom: '1',
      place: '',
      content: '',
      contactPerson: '',
      telephoneNumber: '',
      lat: 0,
      lng: 0,
      endTime: '',
      images:''
    },
    loading: false,
    mshow: false,
    type: '',
    firstfive: [],
    dataList: [],
    isCanDraw: false,
    obj: {},
    bgImg: 'http://linghuoimage.xbbzp.com/FtSQneu0FbMtK5QvJhAWG5_SqvlK',
    code_img: 'http://linghuoimage.xbbzp.com/Fs2WnGKVDZPvdCAnFqhe2y3UrGK7',
    lookdata: {},
    back: false,
    num1: 0,// 发布数
    num2: 0, // 帮助数
    currentDate: new Date().getTime(),
    datetime: false,
    tabs:[
      {
        title:'求助信息',
        name:1
      },
      {
        title:'帮助信息',
        name:2
      }
    ],
    tabActive:1,
    xieyi:false,
    checked:true,
    formshow:false,
    info:0,
    defaultImg:'http://linghuoimage.xbbzp.com/FkxwEQ5X3o53ptw_5LYptOiVuW3H',  // 默认群图片地址
    pageNo:1,
    pageSize:15,
    self_user_id:0,
    hasMore:true,
    loading:false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      lat:getApp().globalData.lat,
      lng:getApp().globalData.lng,
      self_user_id:getApp().globalData.userInfo.id
    })
    this.getNumber()
  },
  onShow(){
    this.data.dataList=[]
    this.data.pageNo=1
    this.loading=false
    this.data.hasMore=true
    this.isGetSetting()
  },
  deletaImg: function (e) {
    //  console.log("-----",e);
    let index = e.detail.index;
    this.data.fileListImg.splice(index, 1);
    this.setData({
      fileListImg: this.data.fileListImg,
    })
  },
  deletaImg1: function (e) {
    //  console.log("-----",e);
    let index = e.detail.index;
    this.data.fileListImg1.splice(index, 1);
    this.setData({
      fileListImg1: this.data.fileListImg1,
    })
  },
  input(event) {
    input.bind(this)(event)
  },
  verify() {
    if(!this.data.checked){
      wx.showToast({
        title: '请先同意协议',
        icon:"none"
      })
      return ;
    }
    let params = JSON.parse(JSON.stringify(this.data.form));
    if (this.data.loading) return;
    this.data.loading = true;
  //   if(!params.type) {
  //     wx.showToast({
  //       title: '类型不能为空',
  //       icon: "none"
  //     })
  //     return false;
  // } 
    if(!params.aidContent) {
      wx.showToast({
        title: '标题不能为空',
        icon: "none"
      })
      this.data.loading = false;
      return false;
  } 
    if(!params.otherDesc) {
      wx.showToast({
        title: '详情不能为空',
        icon: "none"
      })
      this.data.loading = false;
      return false;
  } 
    if(!params.aidPlace) {
      wx.showToast({
        title: '地址不能为空',
        icon: "none"
      })
      this.data.loading = false;
      return false;
  } 
    if(!params.endTime) {
      wx.showToast({
        title: '时间不能为空',
        icon: "none"
      })
      this.data.loading = false;
      return false;
  } 
    if(!params.contactPerson) {
      wx.showToast({
        title: '联系人不能为空',
        icon: "none"
      })
      this.data.loading = false;
      return false;
  } 
    if(!params.telephoneNumber) {
      wx.showToast({
        title: '联系电话不能为空',
        icon: "none"
      })
      this.data.loading = false;
      return false;
  } 
  if(this.data.fileListImg.length > 0){
    this.upDataFile(this.data.fileListImg, 0, 1);
    return false;
  }else if(this.data.fileListImg1.length > 0){
    this.upDataFile(this.data.fileListImg1, 0, 1);
    return false;
  }else{
    this.setData({
      img1:[this.data.defaultImg]
    })
    this.submit()
  }
    // if (!(this.data.fileListImg.length > 0)) {
    //   wx.showToast({
    //     title: '请上传图片',
    //     icon: "none"
    //   })
    //   this.data.loading = false;
    //   return false;
    // }
    // if (this.data.fileListImg.length > 0) {
      
    // }
  },
  dingyue() {
    this.verify();
  },
  submit() {
    wx.showLoading({
      mask: true
    })
    let params = JSON.parse(JSON.stringify(this.data.form));
    params.endTime = this.data.form.endTime + ":00"
    params.images = this.data.img.join(',')
    params.qrCode = this.data.img1.join(',')
    params.userId  =getApp().globalData.userInfo.id
    var that = this;
    if (this.data.form.id) {
      http.updatePost(this.data.factoryJob,
        function (res) {
          wx.hideLoading()
          if (res.success) {
            wx.showModal({
              title: "提示",
              content: "修改岗位信息成功",
              showCancel: false,
              success: function () {
                wx.navigateBack({
                  delta: 1,
                });

              },
            })
          } else {
            wx.showToast({
              title: res.message,
              icon: "none",
            })
          }
        },
        function (err) {
          wx.hideLoading()
        })
    } else {
      console.log("--保存信息--")
      wx.showLoading({
        title: '加载中...',
        mask: true
      })
      http.saveAssistance(params,
        function (res) {
          wx.hideLoading()
          if (res.code == 0) {
            wx.showModal({
              title: "提示",
              content: "发布成功",
              showCancel: false,
              success: function () {
                that.setData({
                  ['form.aidContent']:'',
                  ['form.aidPlace']:'',
                  ['form.otherDesc']:'',
                  ['form.contactPerson']:'',
                  ['form.telephoneNumber']:'',
                  formshow:false
                })
                that.getList()
              },
            })
          } else {
            wx.showToast({
              title: res.message,
              icon: "none",
            })
          }
        },
        function (err) {
          wx.hideLoading()
        })
      this.data.loading = false;
    }
    wx.hideLoading({})
  },
  afterRead(event) {
    const {
      file
    } = event.detail;
    if(file.size>5000000) {
      // 限制文件 5M以内
      wx.showToast({
        title: '文件过大，请重新选择',
        icon:"none"
      })
      return
    }
    if (file.type == "image") {
      file.isNew = true;
      this.setData({
        fileListImg: [...this.data.fileListImg, file],
      })
    } else {
      wx.showToast({
        title: '请上传图片文件',
      })
    }
  },
  afterRead1(event) {
    const {
      file
    } = event.detail;
    if(file.size>5000000) {
      // 限制文件 5M以内
      wx.showToast({
        title: '文件过大，请重新选择',
        icon:"none"
      })
      return
    }
    if (file.type == "image") {
      file.isNew = true;
      this.setData({
        fileListImg1: [...this.data.fileListImg1, file],
      })
    } else {
      wx.showToast({
        title: '请上传图片文件',
      })
    }
  },
  upDataFile(data, index, type) {
    let item = data[index];
    console.log("-----", item);
    var that = this;
    var p = {
      url: item.url,
      name: "file",
      formData: {},
    }
    wx.showLoading({ mask: true })
    http.upDataFile(p,
      function (res) {
        console.log("---上传图片-", res);
        wx.hideLoading({
          success: (res) => { },
        })
        if (res.code == 0) {
          if (type == 1) {
            that.data.img.push(res.data);
            if (index == data.length - 1) {
              if(that.data.fileListImg1.length>0){
                that.upDataFile(that.data.fileListImg1, 0, 2)
              }else{
                that.setData({
                  img1:[that.data.defaultImg]
                })
                that.submit()
              }
            } else {
              console.log("--继续执行--", index, data.length - 1);
              that.upDataFile(data, index + 1, type)
            }
          } else if(type == 2){
            that.data.img1.push(res.data);
            if (index == data.length - 1) {
              that.submit()
              that.data.loading = false;
            }
          }else {
            wx.showToast({
              title: res.message,
              icon: "nene",
            })
            that.data.loading = false;
          }
        }
      },
      function (err) {
        wx.hideLoading()
        that.data.loading = false;
      })
  },
  isGetSetting() {
    // 判断用户是否授权
    var that = this;
    if(this.data.lng){
      that.getList()
      return
    }
    wx.getLocation({
      type: 'gcj02',
      success: function (res) {
        that.setData({
          lat:res.latitude,
          lng:res.longitude,
        })
        getApp().globalData.lng =res.longitude;
        getApp().globalData.lat =res.latitude;
        that.getList()
        console.log("-----用户位置信息--", res)
      },
      fail: function (res) {
        wx.showModal({
          title: '获取当前定位',
          content: '请打开设置，允许小程序使用位置信息',
          cancelText: '不允许',
          confirmText: '打开设置',
          success(res1) {
            if (res1.confirm) {
              wx.openSetting({
                withSubscriptions: true,
                success(res) {
                  if (res.authSetting['scope.userLocation']) {
                    wx.nextTick(() => {
                      that.isGetSetting();
                    })
                  }
                }
              })
            }
          },
          fail(err) {
            console.log(err)
          }
        })
        that.getList()
      },
    })
  },
  aa() {
    console.log(777)
  },
  getList() {
    if(this.data.loading||!this.data.hasMore) return;
    wx.showLoading()
    let params = Object.assign({},this.data.searchQuery)
    params.pageNo=this.data.pageNo;
	  params.pageSize = this.data.pageSize;
	  params.status=[1,2]
	  if (this.data.tabActive == 2) { 
		params.status=[3]
	  }
    var that = this;
    this.data.loading=true
    http.postExpressList(params, res => {
      if (res.code == 0) {
        if(res.data.records.length==0){
          this.data.hasMore=false;
          this.data.loading = false
          return
        }
        res.data.records.filter(item => {
          if (!that.data.lat== 0) {
            let ds = util.getDistance(that.data.lat, that.data.lng, item.lat, item.lng);
            if (ds > 1) {
              item.ds = ds.toFixed(1) + "Km"
            } else {
              item.ds = (ds * 1000).toFixed(0) + "m"
            }
          } else {
            item.ds = "未知"
            item.dst = 0;
          }
          item.endTime = formatTime1(item.endTime)
          item.createTime = formatTime1(item.createTime)
          return item;
        })
        let arr = []
        if (res.data.records.length > 5) {
          arr = res.data.records
        } else {
          arr = [...res.data.records]
        }
        wx.nextTick(() => {
          this.setData({
            dataList: [...this.data.dataList,...res.data.records],
            firstfive: arr,
            loading:false,
            pageNo:this.data.pageNo*1+1
          })
        })
      }
    }, err => { 
      this.data.loading=false
    })
    wx.nextTick(_=>{
      this.data.loading=false
      wx.hideLoading()
    })
  },
  closem1() {
    this.setData({
      mshow: !this.data.mshow
    })
  },
  
  createShareImage() {
    
    wx.previewImage({
      showmenu:true,
      urls: ['http://linghuoimage.xbbzp.com/FkPr0FW-ETAeSAWt-l1wGu-soqsN'],
    })
  },
  maskTel(e) {
    wx.makePhoneCall({
      phoneNumber: e.currentTarget.dataset.tel,
      success() {
      }
    })
  },
  showm(e) {
    wx.navigateTo({
      url: '../searchGDtl/index?id='+e.currentTarget.dataset.id
    })
  },
  backTop() {
    wx.pageScrollTo({
      scrollTop: 0,
      duration: 300,
    })
  },
  onPageScroll(e) {
    if (e.scrollTop > 800 && !this.data.back) {
      this.setData({
        back: true
      })
    }
    if (e.scrollTop < 800 && this.data.back) {
      this.setData({
        back: false
      })
    }
  },
  getNumber() {
    http.postExpressTotal({}, res => {
      this.setData({
        num1: res.data.count,
        num2: res.data.completed
      })
    }, err => { })
  },
  getLocation() {
    let _this = this;
    wx.chooseLocation({
      success(res) {
        console.log(res)
        _this.setData({
          ['form.lat']:res.latitude,
          ['form.lng']:res.longitude,
          ['form.aidPlace']: res.address + ' ' + res.name
        })
      }
    })
  },
  choosetime() {
    this.setData({
      datetime: !this.data.datetime
    })
  },
  choosedate(e) {
    let date = new Date(e.detail)
    // 备选方案
    // let date = e.detail
    this.setData({
      ['form.endTime']: formatTime1(date)
    })
    this.choosetime()
  },
  wc(e){
    var that =this;
    wx.showModal({
      title: "提示",
      content: "确定已经核实过改需求已经完成，不再需要提供帮助？",
      cancelText: '取消',
      confirmText: '确定',
        // if (res1.confirm) {
      showCancel: true,
      success: function (res1) {
        if(res1.cancel){
          return
        }
        let item = e.currentTarget.dataset.item
        http.updateComplete(item.id,res=>{
          if(res.code==0){
            wx.showToast({
              title: '操作成功',
              icon:"none"
            })
            that.getList()
            that.closem1()
          }else{
            wx.showToast({
              title: res.msg,
              icon:"none"
            })
          }
        },err=>{})
      },
    })
    
  },
  toaddr(e){
    let item  = e.currentTarget.dataset.item
    if(!item.aidPlace){ return}
    wx.openLocation({//​使用微信内置地图查看位置。
      latitude: Number(item.lat),//要去的纬度-地址
      longitude:Number(item.lng),//要去的经度-地址
       name: item.aidPlace.split(' ')[0],
      address:item.aidPlace.split(' ')[1]
     })
  },
  onChange(e){
	  this.setData({
      dataList:[],
      pageNo:1,
		hasMore: true,
	  tabActive:e.detail.name
    })
    wx.nextTick(_=>{
      this.getList()
    })

  },
  showxieyi(){
    this.setData({
      xieyi:!this.data.xieyi
    })
  },
  aa(){},
  onChange1(e){
    this.setData({
      checked:e.detail
    })
  },
  publish(){
    this.setData({
      formshow:!this.data.formshow
    })
    wx.pageScrollTo({
      scrollTop:0,
      duration: 100
    })
  },
  getCode(){
    let params={
      path:'pages/index/index',
      param:"route=searchgoods"
    }
    http.createNewCode(params,res=>{
      console.log(res)
    },err=>{})
  },
  tonew(){
    if(!getApp().globalData.userInfo.idNumber){
      wx.showModal({
        title:"提示",
        content:"您还没有实名认证无法报名，是否去实名认证",
        confirmText:"去认证",
        success:function(res){
          if(res.confirm)
          {
            wx.navigateTo({
              url: '/pages/me/pages/realname/realname',
            })
          }
        }
      })
      return ;
    }
    wx.navigateTo({
      url: '../create-goods/index',
    })
  },
  search(){
    this.setData({
      pageNo:1,
      dataList:[]
    })
    this.getList()
  },
  onShareAppMessage: function () {
    var that = this;
    // 设置菜单中的转发按钮触发转发事件时的转发内容
    var code = getApp().globalData.userInfo.inviteCode
    var shareObj = {
      title:'广场', // 默认是小程序的名称(可以写slogan等)
      path: '/pages/index/index?route=searchgoods?code=' + code, // 默认是当前页面，必须是以‘/'开头的完整路径
      imageUrl: '', 
      success: function (res) {
        // 转发成功之后的回调
        if (res.errMsg == 'shareAppMessage:ok') {

        }
      }
    }
    console.log("------------",shareObj);
    // 返回shareObj
    return shareObj;

  },
})